package com.help10000.rms.ui.utils

import android.annotation.SuppressLint
import android.content.Context
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Build
import android.os.Handler
import android.os.Message
import com.amir.common.utils.AppManager
import com.help10000.rms.common.GlobalNetWorkObserver

/**
 * @author justkeepmoving
 */
@SuppressLint("StaticFieldLeak")
object NetWorkUtil {
    private var context: Context? = null

    private var handler: Handler? = null;
    fun init(context: Context) {
        this.context = context
        register(context)
        handler = object : Handler(context.mainLooper) {
            override fun handleMessage(msg: Message) {
                when (msg.what) {
                    1 ->
                        if (!isNetWorkAvailable()) {
                            handler?.post {
                                GlobalNetWorkObserver.displayNoNetworkDialog(
                                    AppManager.getAppManager().currentActivity()
                                )
                            }

                        }
                }
            }
        }
    }

    fun startCountTime() {
        handler?.sendEmptyMessageDelayed(1, 10000)
    }

    fun cancelCountTime() {
        handler?.removeCallbacksAndMessages(null);
    }

    /**
     * 注册广播接受，7.0以上不能在静态注册receiver中接受到此广播
     *
     * @param context
     */
    private fun register(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            cm.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
                override fun onAvailable(network: Network) {
                    isNetAvailable = true
                    val capabilities = cm.getNetworkCapabilities(network)
                    if (capabilities != null) {
                        val isWifi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
                        netWorkType = if (isWifi) 1 else 0
                    } else {
                        netWorkType = -1
                    }
                    cancelCountTime();
                    handler?.post {
                        GlobalNetWorkObserver.cancelDialog()
                    }
                }

                override fun onLost(network: Network) {
                    isNetAvailable = false
                    cancelCountTime();
                    //可能连接了WIFI，流量，先断WIFI，会出现BUG
                    if (!isNetWorkAvailable()) {
                        startCountTime();
                    }
                }
            })
        } else {
            val intentFilter = IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")
            val networkChangeReceiver = NetWorkBroadcastReceiver()
            context.registerReceiver(networkChangeReceiver, intentFilter)
        }
    }

    private var isNetAvailable = false
    private var netWorkType = -1


    fun checkNetWork(context: Context?): Boolean {
        val cm = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val info = cm.activeNetworkInfo
        isNetAvailable = info != null && info.isConnected
        if (info != null) {
            val currentNetWorkType = info.type
            if (currentNetWorkType != netWorkType) {
                netWorkType = currentNetWorkType
            }
        } else {
            netWorkType = -1
        }
        return isNetAvailable
        return false
    }

    fun isNetWorkAvailable(): Boolean {
        return isNetAvailable || checkNetWork(context)
    }

    /**
     * 获取当前可用的网络类型
     *
     * @param context
     * @return
     */
    fun getNetWorkType(): Int {
        return if (netWorkType == -1) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                val cm =
                    context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                        ?: return -1
                val networkInfo = cm.activeNetworkInfo
                if (networkInfo != null && networkInfo.isAvailable) {
                    return networkInfo.type
                }
            }
            -1
        } else {
            netWorkType
        }
    }
}